<template>
  <div class="split-panel-container " :class="open ? 'active': ''">
      <el-card shadow="never" class="heibox">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="持仓" name="1">
                <el-table
                :height="autoH"
                
                :data="list1"
                style="width:100%;"
                >
                    <!-- <el-table-column
                        width="55">
                            <template
                                slot="header"
                                #header="scope"
                            >
                                <el-checkbox v-model="checkedAll" @change="handleSelectionChange"></el-checkbox>
                            </template>

                            <template #default="{ row }">
                                <div>
                                   <el-checkbox v-model="row.checked" ></el-checkbox>
                                </div>
                            </template>
                        </el-table-column> -->
                    <el-table-column prop="uid" label="uid"></el-table-column>
                    <el-table-column prop="username" label="账号"></el-table-column>
                    <el-table-column prop="nickname" label="昵称"></el-table-column>
                    <el-table-column
                        prop="positionnum"
                        label="持仓编号"
                    ></el-table-column>
                    <el-table-column prop="volume" label="持仓数"></el-table-column>
                    <el-table-column prop="contract" label="合约编号"></el-table-column>
                    <el-table-column prop="codename" label="合约名称"></el-table-column>

                    <el-table-column prop="cmd" label="方向">
                        <template #default="{ row }">
                        <div>
                            {{ row.risefall == 'rise' ? '买' : '卖' }}
                        </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="volume" label="下单数量"></el-table-column>
                    <el-table-column prop="playprice" label="持仓价"></el-table-column>
                    <el-table-column prop="yk" label="持仓盈亏">
                        <template #default="{ row }">
                                <div style="text-align:center;" :class="row.yk > 0 ? 'c_red':'c_green'">
                                    {{ row.yk }}
                                </div>
                            </template>
                    </el-table-column>
                    <el-table-column
                        prop="stop_loss_price"
                        label="止损"
                    ></el-table-column>
                    <el-table-column prop="margin" label="保证金"></el-table-column>
                    <el-table-column prop="fee" label="手续费"></el-table-column>
                    <el-table-column prop="rate" label="币种"></el-table-column>
                    <el-table-column prop="rate" label="成交时间">
                        <template #default="{ row }">
                        <div>
                            {{ dayjs.unix(row.updatetime).format('YYYY-MM-DD HH:mm:ss') }}
                        </div>
                        </template>
                    </el-table-column>

                    <el-table-column
                        show-overflow-tooltip
                        fixed="right"
                        align="center"
                        label="操作"
                        width="80"
                    >
                        <template #default="{ row }">
                        <el-button type="text" @click="pingcang(row)">
                            强制平仓
                        </el-button>
                        </template>
                    </el-table-column>

                </el-table>
                <el-pagination
                background
                class="m-t-10"
                :current-page="queryForm.page"
                :layout="layout"
                :total="total"
                @current-change="handleCurrentChange"
                ></el-pagination>
            </el-tab-pane>

            <el-tab-pane label="委托" name="2">
                <el-table
                    v-loading="listLoading"
                    :height="autoH"
                    style="width:100%;"
                    :data="list2"
                    >
                    <el-table-column prop="uid" label="uid"></el-table-column>
                    <el-table-column prop="nickname" label="昵称"></el-table-column>
                    <el-table-column prop="username" label="账号"></el-table-column>
                    <el-table-column prop="wtnum" label="委托编号"></el-table-column>

                    <el-table-column prop="contract" label="合约编号"></el-table-column>
                    <el-table-column prop="codename" label="合约名称"></el-table-column>

                    <el-table-column prop="cmd" label="方向">
                        <template #default="{ row }">
                        <div>
                            {{ row.risefall == 'rise' ? '买' : '卖' }}
                        </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="buynum" label="委托数量"></el-table-column>
                    <el-table-column prop="volume" label="下单数量"></el-table-column>
                    <el-table-column prop="volume" label="持仓数"></el-table-column>
                    <el-table-column prop="playprice" label="持仓价"></el-table-column>
                    <el-table-column prop="yk" label="持仓盈亏">
                        <template #default="{ row }">
                                <div style="text-align:center;" :class="row.yk > 0 ? 'c_red':'c_green'">
                                    {{ row.yk }}
                                </div>
                            </template>
                    </el-table-column>
                    <el-table-column
                        prop="stop_loss_price"
                        label="止损"
                    ></el-table-column>
                    <el-table-column prop="margin" label="保证金"></el-table-column>
                    <el-table-column prop="fee" label="手续费"></el-table-column>
                    <el-table-column prop="rate" label="币种"></el-table-column>
                    <el-table-column prop="rate" label="成交时间">
                        <template #default="{ row }">
                        <div>
                            {{ dayjs.unix(row.updatetime).format('YYYY-MM-DD HH:mm:ss') }}
                        </div>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                background
                class="m-t-10"
                :current-page="queryForm.page"
                :layout="layout"
                :total="total"
                @current-change="handleCurrentChange"
                ></el-pagination>
            </el-tab-pane>

            <el-tab-pane label="成交" name="3">
                <el-table
                    v-loading="listLoading"
                    :height="autoH"
                    :data="list2"
                    style="width:100%;"
                    >
                    <el-table-column prop="uid" label="uid"></el-table-column>
                    <el-table-column prop="nickname" label="昵称"></el-table-column>
                    <el-table-column prop="username" label="账号"></el-table-column>
                    <el-table-column prop="ordernum" label="订单编号"></el-table-column>
                    <el-table-column
                        prop="positionnum"
                        label="成交价格"
                    ></el-table-column>
                    <el-table-column prop="pricetype" label="下单类型">
                        <template #default="{ row }">
                        <div>
                            {{ getType(row) }}
                        </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="volume" label="持仓数"></el-table-column>
                    <el-table-column prop="contract" label="合约编号"></el-table-column>
                    <el-table-column prop="codename" label="合约名称"></el-table-column>

                    <el-table-column prop="cmd" label="方向">
                        <template #default="{ row }">
                        <div>
                            {{ row.risefall == 'rise' ? '买' : '卖' }}
                        </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="volume" label="下单数量"></el-table-column>
                    <el-table-column prop="playprice" label="持仓价"></el-table-column>
                    <el-table-column prop="yk" align="center" label="持仓盈亏">
                             <template #default="{ row }">
                                <div style="text-align:center;" :class="row.yk > 0 ? 'c_red':'c_green'">
                                    {{ row.yk }}
                                </div>
                            </template>
                    </el-table-column>
                    <el-table-column
                        prop="stop_loss_price"
                        label="止损"
                    ></el-table-column>
                    <el-table-column
                        prop="stop_profit_price"
                        label="止盈"
                    ></el-table-column>
                    <el-table-column prop="margin" label="保证金"></el-table-column>
                    <el-table-column prop="fee" label="手续费"></el-table-column>
                    <el-table-column prop="rate" label="币种"></el-table-column>
                    <el-table-column prop="rate" label="成交时间">
                        <template #default="{ row }">
                        <div>
                            {{ dayjs.unix(row.updatetime).format('YYYY-MM-DD HH:mm:ss') }}
                        </div>
                        </template>
                    </el-table-column>
                    
                </el-table>

                <el-pagination
                background
                class="m-t-10"
                :current-page="queryForm.page"
                :layout="layout"
                :total="total"
                @current-change="handleCurrentChange"
                ></el-pagination>
            </el-tab-pane>
         </el-tabs>
      </el-card>
  </div>
</template>

<script>
import { sub, chicang, weituo,chengjiao,qingping } from '@/api/index';
import dayjs from 'dayjs'
import { mapState } from 'vuex';
const zlib = require('zlib');


const unzipBuff = (buffer, cb) => {
	zlib.unzip(buffer, (err, buffer) => {
		if (!err) {
			cb && cb(buffer.toString())
		}
	});
} 


export default {
  data() {
    return {
        dayjs: dayjs,
        $socket: null,
        heartBean: null,
        timer: null,
        listLoading: false,
        checkedAll: false,
        activeName: '1',
        queryForm: {
            uid: '',
            page: 1,
        },
        total: 0,
        layout: 'total, prev, pager, next',
        multipleSelection: [],
        list1: [],
        list2: [],
        list3: [],
        open: false,
    }
  },
  watch: { 
        ticket:{
    　　　　handler: function(val) {
            this.list1 = this.list1.map( item => {
                let currentItem = val.find( data => {
                    return  data.M + data.S + data.C == item.contract
                })
                if (currentItem) {
                    if (item.risefall == 'rise') {
                        item.newPrice = currentItem.B1
                    } else {
                        item.newPrice = currentItem.S1
                    }
                    item = {...item, ...currentItem}
                } 
                let yk = this.getYK(item)
                item.yk = yk
                return item
                })
           this.multipleSelection =  this.list1.filter( item => item.checked).map(item => item)   
             
    　　　},
        immediate: true,
    　　　 deep:true
　　    },
    },
    
  computed: {
        autoH() {
            return window.innerHeight - 350
        },
        ...mapState({
            ticket: state => state.ticket /*,, 推送数据 */,
            userInfo: state => state.userInfo,
            zijinSet: state => state.zijinSet
        })
  },
  
  methods: {
      closePage() {
           if (this.heartBean) {
                clearInterval(this.heartBean)
            }
            // 导航离开该组件的对应路由时调用
            this.$socket && this.$socket.close() 
      },
      getAllList() {
          this.fetch1()
          this.fetch2()
          this.fetch3()
      },
      async fetch1() {
         this.listLoading = true
         const res =  await chicang({uid: this.queryForm.uid, page: this.queryForm.page})
         this.listLoading = false
         this.list1 = res.data.list.map( item => {
            const taDa = this.list1.find(da => da.id == item.id)
            if (taDa) {
                item.checked = taDa.checked
            } else {
                item.checked = false
            }
            return item
        });
        this.total = res.data.total
      },
      async fetch2() {
         this.listLoading = true
         const res =  await weituo({uid: this.queryForm.uid, page: this.queryForm.page})
         this.listLoading = false
          this.list2 = res.data.list
          this.toatl = res.data.total
      },
      async fetch3() {
          this.listLoading = true
          const res =  await chengjiao({uid: this.queryForm.uid, page: this.queryForm.page})
          this.listLoading = false
          this.list3 = res.data.list
          this.toatl = res.data.total
      },
      close() {
           this.open = false
      },
           // 多选操作
        handleSelectionChange() {
            if (this.checkedAll) {
                this.list1 = this.list1.map( item => {
                    item.checked = true
                    return item
                })
            } else {
                 this.list1 = this.list1.map( item => {
                    item.checked = false
                    return item
                })
            }
            
        },
      getYK(item) {
            let dc = 0
            if (!item || !item.N) {
                return dc
            }
            let p = 0
            if (item.risefall == 'rise') {
                if (item.N.indexOf('日元') > -1) {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(7)
                } else if (item.N.indexOf('欧元') > -1) {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(5)
                } else {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(3)
                }
                
                if (dc == 0) {
                    p = 0
                
                    return p
                }
                
                if (item.N.indexOf('日元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
                
                    return  p
                } else if (item.N.indexOf('欧元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
                
                    return  p
                } else {
                    p =  (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
                
                    return p
                }
            } else {
                if (item.N.indexOf('日元') > -1) {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(7)
                } else if (item.N.indexOf('欧元') > -1) {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(5)
                } else {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(3)
                }
                
                if (dc == 0) {
                    p = 0
                
                    return p
                }
                if (item.N.indexOf('日元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
                
                    return  p
                } else if (item.N.indexOf('欧元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
                
                    return  p
                } else {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
                
                    return  p
                }
            }
            
            },
        conn: function(conn) {
            let connection =  'ws://120.79.84.58:9501/id/'
            connection += conn
            if (!this.$socket) {
                if (typeof WebSocket == 'undefined') {
                    console.error('当前浏览器不支持websocket');
                    return false;
                }

                if (!connection) {
                    console.error('[mysocket] cannot locate connection');
                    return false;
                }
                this.$socket = new WebSocket(connection);
                this.$socket.onopen = (e) => {
                    this.onopen()
                };
                this.$socket.onmessage = (e) => {
                   // this.onmessage(JSON.parse(e.data) )
                    var buffer = new Buffer(e.data, 'base64');
                    unzipBuff(buffer, (res) => {
                        this.onmessage(JSON.parse(res))
                    })
                };

                this.$socket.onclose = (e) => {
                    this.onclose()
                };
            } else {
                this.$socket.close()

            }
        },
        onopen() {
            this.loadSymbol()
            this.sendHeartBean()
        },
        onmessage(data) {
            if (data.Cmd == 'all') {
                this.$store.commit('setTicket', data.data.filter( item => !!item).map( item => item));
            }
            /*var buffer = new Buffer(data, 'base64');
            unzipBuff(buffer, (da) => {
                
            })*/
        },
        onclose() {
            this.$socket = null
            clearInterval(this.heartBean)
            this.timer && clearInterval(this.timer)
            this.heartBean = null
        },
        loadSymbol() {
            sub({subcode: 'All', uid: localStorage.getItem('deviceid')}).then(res => {
            })
		},
        getContactlist() {
            contactlist({}).then(res => {
                if (res.code == 1) {
                    this.$store.commit('setContactList', res.data);
                } 
            })
        },
        createHash (hashLength) {
            if (!hashLength || typeof(Number(hashLength)) != 'number') {return;}
            let ar = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
            let hs = [];
            let hl = Number(hashLength);
            let al = ar.length;
            for (let i = 0; i < hl; i ++) {
                hs.push(ar[Math.floor(Math.random() * al)]);
            }
            return hs.join('');
        },
        sendHeartBean() {
            if (this.heartBean) {
                clearInterval(this.heartBean)
            }
            this.heartBean = setInterval( () => {
                this.$socket.send(JSON.stringify({ Cmd: 'heartbeat', uid: localStorage.getItem('deviceid') }));
            }, 5000)
        
        },
        connect() {
            this.conn(localStorage.getItem('deviceid'));
        },
        getDeviceid() {
            getdeviceid({hashid: this.hashid}).then(res => {
                if (res.code == 1) {
                    const { appid } = res.data
                    localStorage.setItem('deviceid', appid);
                    this.connect()
                } 
            })
        },
        init() {
            if (localStorage.getItem('deviceid') == 'null' || !localStorage.getItem('deviceid')) {
                this.hashid =  this.createHash(18)
                this.getDeviceid()
            } else {
                this.connect()
            }
        },
       getType(row) {
        if (row.pricetype == 1) {
          return '快捷下单'
        } else if (row.pricetype == 2) {
          return '三键下单'
        } else {
          return '传统下单'
        }
      },
      showEdit(row) {
          this.queryForm.uid = row.id
          this.getAllList()
          this.timer = setInterval(() => {
            this.getAllList()
          }, 10000);
          this.open = true
      },
      pingcang(row) {
            this.$confirm('确定强制平仓吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }).then(() => {
                qingping({wtnum: row.wtnum}).then(res => {
                        this.$message.success(res.msg)
                        this.handleCurrentChange(1)
                        this.$emit('fetch-data')
                    }).catch(ret => {
                        this.$message.error(ret.msg)
                    })
            })
        },
      handleCurrentChange(page) {
          this.queryForm.page = page
          this.getAllList()
      },
      handleClick() {

      },
  }
}
</script>


<style scoped lang="scss">
::v-deep .heibox {
    
    .el-card__body{
        height: calc(100vh - 270px);
    }
}
.split-panel-container {
    width: 0;
    overflow: hidden;
    &.active {
        width:calc(100% - 550px);
    }
    
}
.c_red {
    color: #ff0000 !important;
}
.c_green {
    color: green !important;
}
.m-t-10 {margin-top: 10px;}
</style>
